package com.central.task.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.central.task.mapper.QuoteUdfMapper;
import com.central.task.mapper.ResourceInfoMapper;
import com.central.task.mapper.UdfDefinedMapper;
import com.central.task.model.QuoteUdf;
import com.central.common.enums.ResourceType;
import com.central.task.service.IResourceManageService;
import com.central.task.service.IUdfDefinedService;
import com.central.common.model.ResourceInfo;
import com.central.common.model.Result;
import com.central.common.model.SysUser;
import com.central.common.model.UdfDefined;
import com.central.common.service.impl.SuperServiceImpl;
import com.central.common.utils.UserRoleUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * @author Tindy
 * @date 2021/11/29
 * @describe
 */
@Slf4j
@Service
public class UdfDefinedServiceImpl extends SuperServiceImpl<UdfDefinedMapper, UdfDefined> implements IUdfDefinedService {
    @Autowired
    private QuoteUdfMapper quoteUdfMapper;
    @Autowired
    private IResourceManageService resourceManageService;
    @Autowired
    private ResourceInfoMapper resourceInfoMapper;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Result saveOrUpdateUdf(SysUser user, UdfDefined udf) {
        if(udf.getId()!=null){
            //仅函数创建者或项目管理员可编辑
            UdfDefined udf2 = getById(udf.getId());
            if(!udf2.getProId().equals(user.getCurrentProjectId())) return Result.failed("操作失败：" + "该udf非当前项目，无权限");
            if(!user.getUsername().equals(udf2.getCreator()) && !UserRoleUtil.checkProAdmin(user.getProRoles())){
                return Result.failed("操作失败：" + "非该udf的创建者或项目管理员无权限操作");
            }
            udf.setCreator(udf2.getCreator());
            ArrayList<Long> quoteIds = new ArrayList<>();
            quoteIds.add(udf2.getResourceQuoteId());
            resourceManageService.delQuotes(quoteIds);
        }else {
            udf.setCreator(user.getUsername());
        }
        udf.setProId(user.getCurrentProjectId());
        ResourceInfo resourceInfo = resourceInfoMapper.selectById(udf.getResourceId());
        if(resourceInfo.getResourceType()!=ResourceType.JAR) return Result.failed("操作失败：" + "引用的文件非JAR类型");
        udf.setResourceName(resourceInfo.getName());
        udf.setResourceUrl(resourceInfo.getFileUrl());
        Long quoteId = resourceManageService.quoteResource(udf.getResourceId(), "被项目 " + udf.getProId() + " 的 " + udf.getName() + " udf 引用");
        udf.setResourceQuoteId(quoteId);
        saveOrUpdate(udf);
        return Result.succeed("操作成功");
    }

    @Override
    public List<UdfDefined> findUdfs(Long proId) {
        return baseMapper.selectList(new QueryWrapper<UdfDefined>().eq("pro_id",proId).orderByDesc("id"));
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Result delete(SysUser user, Long id) {
        UdfDefined udfDefined = getById(id);
        if (!udfDefined.getProId().equals(user.getCurrentProjectId())) return Result.failed("操作失败：" + "该文件非当前项目，无权限");
            //判断该udf是否被引用
            QuoteUdf quoteUdf = findQuote(id);
            if (quoteUdf != null) {
                return Result.failed("操作失败：该资源被引用，" + quoteUdf.getMsg());
            }
            if(udfDefined.getCreator().equals(user.getUsername()) || UserRoleUtil.checkProAdmin(user.getProRoles())){
                removeById(id);
                ArrayList<Long> quoteIds = new ArrayList<>();
                quoteIds.add(udfDefined.getResourceQuoteId());
                resourceManageService.delQuotes(quoteIds);
            }else {
                return Result.failed("操作失败："+"非该文件的创建者或项目管理员无权限操作");
            }
            return Result.succeed("操作成功");

    }

    @Override
    public List<UdfDefined> findUdfsByIds(List<Long> ids) {
        return baseMapper.selectBatchIds(ids);
    }

    private QuoteUdf findQuote(Long id) {
        return quoteUdfMapper.selectOne(new QueryWrapper<QuoteUdf>().eq("udf_id",id));
    }
}
